<template>
  <div class="app-windows">
    <div
      v-for="window in windows"
      :key="window.id"
      class="app-window"
      :class="{
        active: activeWindow === window.id,
        minimized: window.minimized,
        maximized: window.maximized,
      }"
      :style="{
        left: window.position.x + 'px',
        top: window.position.y + 'px',
        width: window.maximized ? '100vw' : window.size.width + 'px',
        height: window.maximized ? '100vh' : window.size.height + 'px',
        zIndex: activeWindow === window.id ? 1000 : 999,
      }"
      @mousedown="activateWindow(window.id)"
    >
      <!-- 窗口标题栏 -->
      <div
        class="window-header"
        @mousedown="startDrag($event, window.id)"
        @dblclick="toggleMaximize(window.id)"
      >
        <div class="window-title">
          <span class="window-icon">{{ window.app.icon }}</span>
          <span class="window-name">{{ window.app.name }}</span>
        </div>
        <div class="window-controls">
          <button
            class="window-control minimize"
            @click="minimizeWindow(window.id)"
            title="最小化"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
              <path d="M5 12h14" />
            </svg>
          </button>
          <button
            class="window-control maximize"
            @click="toggleMaximize(window.id)"
            title="最大化"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
              <path
                d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"
              />
            </svg>
          </button>
          <button
            class="window-control close"
            @click="closeWindow(window.id)"
            title="关闭"
          >
            <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor">
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>
      </div>

      <!-- 窗口内容 -->
      <div class="window-content">
        <component
          :is="window.component"
          v-bind="window.props"
          @close="closeWindow(window.id)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, markRaw } from "vue";
import FamilyManagement from "./FamilyManagement.vue";
import AccountingManagement from "./accounting/AccountingManagement.vue";
import UnifiedFuelManagement from "./fuel/UnifiedFuelManagement.vue";
import ScheduleManagement from "./schedule/ScheduleManagement.vue";
import { useScheduleStore } from "@/stores/schedule";
import type { App } from "@/types/common";

// 窗口类型定义
interface WindowState {
  id: string;
  app: {
    id: string;
    name: string;
    icon?: string;
  };
  component: Component;
  props?: Record<string, unknown>;
  position: { x: number; y: number };
  size: { width: number; height: number };
  minimized: boolean;
  maximized: boolean;
}

// 组件类型
type Component = {
  __name?: string;
  [key: string]: unknown;
};

// 定义组件事件
const emit = defineEmits<{
  close: [windowId: string];
}>();

// 窗口状态
const windows = ref<WindowState[]>([]);
const activeWindow = ref<string | null>(null);

// 拖拽状态
const dragState = ref({
  isDragging: false,
  currentWindow: "",
  startX: 0,
  startY: 0,
  startLeft: 0,
  startTop: 0,
});

// 计算下一个窗口位置
const getNextWindowPosition = () => {
  const offset = windows.value.length * 30;
  return {
    x: Math.min(
      100 + offset,
      (typeof window !== "undefined" ? window.innerWidth : 1200) - 400,
    ),
    y: Math.min(
      100 + offset,
      (typeof window !== "undefined" ? window.innerHeight : 800) - 300,
    ),
  };
};

// 打开新窗口
const openWindow = (
  appId: string,
  app: App,
  component: Component,
  props?: Record<string, unknown>,
) => {
  const position = getNextWindowPosition();

  const newWindow: WindowState = {
    id: `${appId}-${Date.now()}`,
    app: {
      id: appId,
      name: app.name,
      icon: app.icon,
    },
    component: markRaw(component),
    props,
    position,
    size: {
      width: 800,
      height: 600,
    },
    minimized: false,
    maximized: false,
  };

  windows.value.push(newWindow);
  activeWindow.value = newWindow.id;
};

// 激活窗口
const activateWindow = (windowId: string) => {
  activeWindow.value = windowId;
};

// 关闭窗口
const closeWindow = (windowId: string) => {
  const index = windows.value.findIndex((w) => w.id === windowId);
  if (index > -1) {
    windows.value.splice(index, 1);
    emit("close", windowId);

    // 如果关闭的是活跃窗口，激活另一个窗口
    if (activeWindow.value === windowId) {
      activeWindow.value =
        windows.value.length > 0
          ? windows.value[windows.value.length - 1].id
          : null;
    }
  }
};

// 最小化窗口
const minimizeWindow = (windowId: string) => {
  const windowObj = windows.value.find((w) => w.id === windowId);
  if (windowObj) {
    windowObj.minimized = true;
    if (activeWindow.value === windowId) {
      activeWindow.value = null;
    }
  }
};

// 切换最大化
const toggleMaximize = (windowId: string) => {
  const windowObj = windows.value.find((w) => w.id === windowId);
  if (windowObj) {
    windowObj.maximized = !windowObj.maximized;
  }
};

// 开始拖拽
const startDrag = (event: MouseEvent, windowId: string) => {
  const windowObj = windows.value.find((w) => w.id === windowId);
  if (!windowObj || windowObj.maximized) return;

  dragState.value = {
    isDragging: true,
    currentWindow: windowId,
    startX: event.clientX,
    startY: event.clientY,
    startLeft: windowObj.position.x,
    startTop: windowObj.position.y,
  };

  activateWindow(windowId);

  document.addEventListener("mousemove", handleDrag);
  document.addEventListener("mouseup", stopDrag);
};

// 处理拖拽
const handleDrag = (event: MouseEvent) => {
  if (!dragState.value.isDragging) return;

  const windowObj = windows.value.find(
    (w) => w.id === dragState.value.currentWindow,
  );
  if (!windowObj) return;

  const deltaX = event.clientX - dragState.value.startX;
  const deltaY = event.clientY - dragState.value.startY;

  windowObj.position.x = Math.max(
    0,
    Math.min(
      windowObj.position.x + deltaX,
      (typeof window !== "undefined" ? window.innerWidth : 1200) -
        windowObj.size.width,
    ),
  );
  windowObj.position.y = Math.max(
    0,
    Math.min(
      windowObj.position.y + deltaY,
      (typeof window !== "undefined" ? window.innerHeight : 800) -
        windowObj.size.height,
    ),
  );

  dragState.value.startX = event.clientX;
  dragState.value.startY = event.clientY;
  dragState.value.startLeft = windowObj.position.x;
  dragState.value.startTop = windowObj.position.y;
};

// 停止拖拽
const stopDrag = () => {
  dragState.value.isDragging = false;
  document.removeEventListener("mousemove", handleDrag);
  document.removeEventListener("mouseup", stopDrag);
};

// 处理键盘事件
const handleKeyDown = (event: KeyboardEvent) => {
  // 如果按下了ESC键且有活跃的窗口
  if (event.key === "Escape" && activeWindow.value) {
    // 检查页面上是否有任何模态框打开
    const hasModal = document.querySelector(".modal-overlay") !== null;

    // 如果有模态框，让模态框自己处理ESC键
    if (hasModal) {
      return;
    }

    // 没有模态框时才关闭窗口
    closeWindow(activeWindow.value);
  }
};

// 组件方法
const openFamilyManagement = (app: App) => {
  openWindow("family", app, FamilyManagement);
};

const openAccountingManagement = (app: App) => {
  openWindow("accounting", app, AccountingManagement);
};

const openUnifiedFuelManagement = (app: App) => {
  openWindow("fuel-records", app, UnifiedFuelManagement);
};

const scheduleStore = useScheduleStore();

const openScheduleManagement = (app: App) => {
  openWindow("schedule", app, ScheduleManagement, {
    schedules: scheduleStore.schedules
  });
};

// 添加键盘事件监听器
onMounted(() => {
  document.addEventListener("keydown", handleKeyDown);
});

// 移除键盘事件监听器
onUnmounted(() => {
  document.removeEventListener("keydown", handleKeyDown);
});

// 暴露方法给父组件
defineExpose({
  openFamilyManagement,
  openAccountingManagement,
  openUnifiedFuelManagement,
  openScheduleManagement,
});
</script>

<style lang="scss" scoped>
@use "../styles/variables" as *;
@use "../styles/mixins" as *;

.app-windows {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: $z-index-modal;
}

.app-window {
  position: absolute;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: var(--el-border-radius-base);
  box-shadow: var(--el-box-shadow);
  overflow: hidden;
  pointer-events: all;
  transition: box-shadow 0.2s ease;

  &.active {
    box-shadow: var(--el-box-shadow-dark);
  }

  &.minimized {
    display: none;
  }

  &.maximized {
    border-radius: 0;
    border: none;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
  }
}

.window-header {
  @include flex-between;
  align-items: center;
  padding: 8px 16px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color);
  cursor: move;
  user-select: none;
}

.window-title {
  @include flex-center;
  gap: 4px;
  flex: 1;
}

.window-icon {
  font-size: 16px;
}

.window-name {
  font-size: 12px;
  font-weight: 500;
  font-family:
    -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.window-controls {
  @include flex-center;
  gap: 4px;
}

.window-control {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  @include flex-center;
  transition: all 0.2s ease;

  &.minimize {
    background: #ffbd2e;

    &:hover {
      background: #e0a520;
    }
  }

  &.maximize {
    background: #28ca42;

    &:hover {
      background: #22a837;
    }
  }

  &.close {
    background: #ff5f56;

    &:hover {
      background: #e0453e;
    }
  }

  svg {
    width: 8px;
    height: 8px;
    color: rgba(255, 255, 255, 0.8);
  }
}

.window-content {
  height: calc(100% - 40px);
  overflow: auto;
  background: var(--el-bg-color);
}

@include mobile {
  .app-window {
    left: 0 !important;
    top: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    border-radius: 0;
    border: none;
  }

  .window-header {
    cursor: default;
  }
}
</style>
